<template>
  <div style="position: relative">
    <el-form
      :inline="true"
      size="mini"
      :model="formInline"
      label-position="right"
    >
      <el-form-item label="商机名称">
        <el-input
          class="filter-item"
          v-model="formInline.oppoName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业电话">
        <el-input
          class="filter-item"
          v-model="formInline.telephone"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="商机状态">
        <el-select
          v-model="formInline.oppoStatus"
          clearable
          placeholder="请选择"
        >
          <el-option label="立项前" value="1"></el-option>
          <el-option label="投标中" value="2"></el-option>
          <el-option label="赢单申请中" value="5"></el-option>
          <el-option label="已立项" value="3"></el-option>
          <el-option label="已完成" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="times"
          type="daterange"
          align="right"
          unlink-panels
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="selecttime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onSubmit">搜索</el-button>
        <el-button
          type="warning"
          class="el-button--reset"
          icon="el-icon-refresh-right"
          @click="resetFromdata"
          size="mini"
        ></el-button>
        <!-- <el-button type="primary" size="mini" @click="addFromdata"
          >创建商机</el-button
        > -->
        <el-button type="primary" size="mini" @click="exportForm"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div class="total">
          <div class="total-item" :class="{'active': partner === ''}" @click="handleClickTotal('')">全部（{{ countInfo.all || 0 }}）</div>
          <div class="total-item" :class="{'active': partner === '11'}" @click="handleClickTotal('11')">我创建的商机（{{ countInfo.setUp || 0 }}）</div>
          <div class="total-item" :class="{'active': partner === '10'}" @click="handleClickTotal('10')">我协作的商机（{{ countInfo.coo || 0 }}）</div>
          <div class="total-item" :class="{'active': partner === '3'}" @click="handleClickTotal('3')">已立项（{{ countInfo.project || 0 }}）</div>
          <div class="total-item" :class="{'active': partner === '4'}" @click="handleClickTotal('4')">已完成（{{ countInfo.good || 0 }}）</div>
        </div>
        <el-table
          :data="tableData"
          size="mini"
          style="width: 100%"
          header-cell-class-name="table-header-gray"
          v-loading="isShowloading"
          border
        >
          <el-table-column
            type="index"
            align="center"
            width="55"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="oppoName"
            align="center"
            width="150"
            label="商机名称"
          >
            <template slot-scope="{ row }">
              <el-tooltip
                class="item"
                effect="dark"
                :content="row.oppoName"
                placement="top-start"
              >
                <div class="table-tag">
                  <div class="oppo-name">
                    {{ row.oppoName }}
                  </div>
                  <el-tag
                    size="small"
                    v-if="
                      row.createOrCollaborate && row.createOrCollaborate !== 1
                    "
                    >{{ row.createOrCollaborate | roleFilter }}</el-tag
                  >
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="custName"
            align="center"
            label="企业名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="telephone"
            align="center"
            label="企业电话"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="oppoStatusName"
            align="center"
            label="商机状态"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="oppoDistrictName"
            align="center"
            label="所在地区"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="businessTypeName"
            align="center"
            label="业务类型"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            width="140"
          ></el-table-column>
          <el-table-column
            prop="createUserName"
            align="center"
            label="创建人"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="contractAmount"
            align="center"
            label="预计合同额度"
            width="150"
          >
            <template slot-scope="scope">
                <div> {{scope.row.contractAmount ? scope.row.contractAmount : 0 }} {{scope.row.units}} </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="220"
          >
            <template slot-scope="scope">
              <!-- <el-button
                type="text"
                v-if="scope.row.showEditor === 1"
                @click="handleClickEdit(scope.row)"
                >编辑</el-button
              > -->
              <el-button type="text" @click="handleInfo(scope.row)"
                >审核</el-button
              >
              <!-- <el-button
                type="text"
                v-if="scope.row.show"
                @click="handleClickApply(scope.row)"
                >赢单申请</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.processed == 1"
                @click="handleClickExamine(scope.row)"
                >待处理</el-button
              >
              <el-button
                type="text"
                @click="handleDelete(scope.row)"
                v-if="
                  scope.row.oppoStatus == 1 && scope.row.createOrCollaborate === 3
                "
                >删除</el-button
              > -->
              <span v-if="scope.row.winSingle1 == 1" style="color: #F56C6C;margin-left: 10px">已赢单</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-size="page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog
      title="赢单申请"
      :visible.sync="applyDialog"
      width="600px"
      destroy-on-close
    >
      <!-- 添加 -->
      <el-form
        :model="applyData"
        ref="winSingleForm"
        size="mini"
        label-position="right"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="申请理由：" prop="note">
              <el-input
                type="textarea"
                v-model="applyData.note"
                placeholder="请输入理由，说明商机目前推进情况"
                maxlength="150"
                :rows="3"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抄送：" prop="executorList">
              <approver
                v-if="applyData.executorList"
                ref="approver"
                :isCc="true"
                :approverList="applyData.executorList"
                :getUserFn="$BusinessOpportunities.selectDivision"
                @handleChooseapprover="handleChooseExecutorList"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="applyDialog = false; resetForm();">取 消</el-button>
        <el-button type="primary" @click="handleClickApplySubmit"
          >确认申请</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { BusinessOpportunities } from '@/api/commercial.js';
import { EcologicalkKnowledge } from '@/api/knowledgeBases.js';
import { Businesstype } from '@/api/business.js';
import approver from '../Projects/components/approver';
export default {
  name: 'Opportunities',
  filters: {
    roleFilter (val) {
      const data = {
        1: '普通',
        2: '协作',
        3: '创建'
      };
      return data[val];
    }
  },
  components: {
    approver
  },
  data () {
    return {
      businesstypeTree: [],
      businesstypeId: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true
      },
      editDialogVisible: false,
      formInline: {
        directorName: null,
        oppoCode: null,
        oppoName: null,
        customerName: null,
        contacts: null,
        createTime1: null,
        createEndTime1: null,
        businessType: null,
        stage: null,
        oppoStatus: null,
        oppoDistrictCode: null
      },
      tableData: [],
      total: 0,
      page_size: 10,
      pageNo: 1,
      isShowloading: false,
      areaCodelist: [],
      areaCodes: [],
      areaCodeprops: {
        label: 'name',
        value: 'id',
        children: 'children',
        checkStrictly: true
      },
      times: '',
      countInfo: {},
      applyData: {
        executorList: []
      },
      applyDialog: false,
      applyId: '',
      partner: ''
    };
  },
  mounted () {
    // this.loadareaCodelistDict()
    this.loadClueWidgetData()
    // this.loadbusinesstypeTree()
  },
  activated () {
    this.loadClueWidgetData(); // 数据加载的方法
  },
  computed: {},
  methods: {
    // 赢单申请，选择抄送人
    handleChooseExecutorList (data) {
      data = data.map(v => v.userId);
      this.applyData.executorList = data;
    },
    handleClickTotal (val) {
      if (val === '10' || val === '11') {
        this.formInline.partner = val
      } else {
        this.formInline.partner = ''
      }
      if (val === '3' || val === '4') {
        this.formInline.oppoStatus = val
      } else {
        this.formInline.oppoStatus = ''
      }
      this.partner = val
      this.pageNo = 1;
      this.loadClueWidgetData()
    },
    // 赢单申请
    handleClickApplySubmit () {
      console.log(this.applyData);
      BusinessOpportunities.applicationApply(this, {
        ...this.applyData,
        id: this.applyId
      }).then((res) => {
        this.loadClueWidgetData();
        this.$message({
          type: 'success',
          message: '已提交'
        });
        this.applyDialog = false;
        this.resetForm();
      });
    },
    handleClickApply (row) {
      this.applyId = row.id;
      this.applyDialog = true;
    },
    // 选择创建时间
    selecttime (times) {
      if (times) {
        this.formInline.createTime1 = times[0];
        this.formInline.createEndTime1 = times[1];
      } else {
        this.formInline.createTime1 = '';
        this.formInline.createEndTime1 = '';
      }
    },
    /**
     * 行政区划
     */
    loadareaCodelistDict () {
      return new Promise((resolve, reject) => {
        EcologicalkKnowledge.listDict(this)
          .then((res) => {
            let areaCodelist = res.data;
            let areaCodelistnew = [];
            areaCodelist.forEach((item, index) => {
              if (!item.parentId) {
                item.children = [];
                areaCodelistnew.push(item);
              }
            });
            areaCodelistnew.forEach((item1, index1) => {
              let info = areaCodelist.find((item2, index2) => {
                return item1.id === item2.parentId;
              });
              if (info) {
                item1.children = [];
                areaCodelist.forEach((item3, index3) => {
                  if (item1.id === item3.parentId) {
                    item1.children.push(item3);
                  }
                });
              } else {
                item1.children = null;
              }
            });
            areaCodelistnew.forEach((item4, index4) => {
              if (item4.children) {
                item4.children.forEach((item5, index5) => {
                  let info2 = areaCodelist.find((item6, index6) => {
                    return item5.id === item6.parentId;
                  });
                  if (info2) {
                    item5.children = [];
                    areaCodelist.forEach((item7, index7) => {
                      if (item5.id === item7.parentId) {
                        item5.children.push(item7);
                      }
                    });
                  } else {
                    item5.children = null;
                  }
                });
              }
            });
            this.areaCodelist = areaCodelistnew;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },

    /**
     * 选择行政区划
     */
    areaCodesChange () {
      let info = this.areaCodes;
      let length = info.length - 1;
      this.formInline.oppoDistrictCode = info[length];
      this.$refs['ref_areaCodes'].dropDownVisible = false;
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this)
          .then((res) => {
            this.businesstypeTree = res.data;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    businessChange () {
      let info = this.businesstypeId;
      let length = info.length - 1;
      this.formInline.businessType = info[length];
      this.$refs['ref_business'].dropDownVisible = false;
    },
    /**
     * 商机列表
     */
    loadClueWidgetData () {
      let params = {
        ...this.formInline,
        selectExamine: 'examine',
        size: this.page_size,
        current: this.pageNo
      };
      return new Promise((resolve, reject) => {
        BusinessOpportunities.list(this, params)
          .then((res) => {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
            this.countInfo = res.data.count
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    // 搜索
    onSubmit () {
      this.pageNo = 1;
      this.loadClueWidgetData();
    },
    // 重置
    resetFromdata () {
      this.formInline = {
        directorName: null,
        oppoCode: null,
        oppoName: null,
        customerName: null,
        contacts: null,
        createTime1: null,
        createEndTime1: null,
        businessType: null,
        stage: null,
        oppoStatus: null,
        oppoDistrictCode: null
      };
      this.partner = ''
      this.pageNo = 1;
      this.page_size = 10;
      this.loadClueWidgetData();
    },
    // 分页导航
    handleCurrentChange (val) {
      this.pageNo = val;
      this.loadClueWidgetData();
    },
    handleSizeChange (val) {
      this.page_size = val;
      this.loadClueWidgetData();
    },
    currentChange (val) {
      this.pageNo = val;
      this.loadClueWidgetData();
    },
    // 创建商机
    addFromdata () {
      this.$router.push('/Opportunitiesadd');
    },
    // 导出
    exportForm () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo
      };
      return new Promise((resolve, reject) => {
        BusinessOpportunities.ExportFile(this, params, '商机管理明细表.xlsx');
      });
    },
    // 查看
    handleInfo (row) {
      this.$router.push({
        path: '/OpportunitiesDetail',
        query: { oppoId: row.id }
      });
    },
    handleClickEdit (row) {
      this.$router.push({
        path: '/Opportunitiesadd',
        query: {
          oppoId: row.id
        }
      });
    },
    // 赢单
    handleWinasingle (row) {
      return new Promise((resolve, reject) => {
        BusinessOpportunities.checkTaskComplete(this, row.id)
          .then((res) => {
            if (res.data) {
              this.$router.push({
                path: '/Winasingle',
                query: { oppoId: row.id }
              });
            } else {
              this.$message({
                showClose: true,
                message: '任务全部完成才可进行此操作！',
                type: 'warning'
              });
            }
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    // 处理赢单申请
    handleClickExamine (row) {
      this.$router.push({
        path: '/Opportunitiesitem',
        query: {
          oppoId: row.id
        }
      })
    },
    // 修改
    handleEdit (row) {
      this.$router.push({
        path: '/Opportunitiesadd',
        query: { oppoId: row.id }
      });
    },
    // 删除
    handleDelete (row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = row.id;
        return new Promise((resolve, reject) => {
          BusinessOpportunities.delete(this, params)
            .then((res) => {
              this.loadClueWidgetData();
            })
            .catch((e) => {
              reject(e);
            });
        });
      });
    },
    resetForm () {
      this.$refs['winSingleForm'].resetFields();
      this.$refs.approver.reset();
    }
  }
};
</script>
<style lang="scss" scoped>
.total {
  display: flex;
  align-items: center;
  .total-item {
    padding: 10px;
    cursor: pointer;
    transition: color 0.3s;
    &:hover {
      color: #409eff;
    }
    &.active {
      color: #409EFF;
    }
  }
}
.table-tag {
  display: flex;
  justify-content: center;
  .oppo-name {
    width: 0;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
